﻿using HslCommunication.Profinet.Siemens;
using HslCommunication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace paraInterface
{
    internal class Siemens300PLC_C:PLC
    {
        public SiemensS7Net SiemensPLC { get; set; }
        Dictionary<string, string> dict = new Dictionary<string, string>();
        public bool isConnected = false;
        public override bool InitPLC()
        {
            if (IsIP(IP))
            {
                SiemensPLC = new SiemensS7Net(SiemensPLCS.S300, IP);
                SiemensPLC.ConnectTimeOut = 5000;
                isRealPLC = true;
                for (int i = 0; i < DATALENTH; i++)
                {
                    dict.Add("Z" + i.ToString().PadLeft(3, '0'), "0");
                }
            }
            return isRealPLC;
        }

        public override bool SendData2PLC(jsonData data)//需要将数据进行解析
        {
            int res = 0;
            if (Connect2PLC())
            {
                try
                {
                    //将数据进行解析发送到PLC
                    //梳理数据
                    for (int i = 0; i < data.PARAMS.Length && i < DATALENTH; i++)
                    {
                        if (Convert.ToInt32(data.PARAMS[i].TBGD_ITEM_CODE.Substring(1)) != (i + 1))
                            return false;
                        dict[data.PARAMS[i].TBGD_ITEM_CODE] = data.PARAMS[i].TBGD_UPPER_LIMIT;
                    }

                    short[] v1 = new short[32];
                    for (int i = 0; i < DATALENTH; i++)
                    {
                        v1[i] = Convert.ToInt16("0" + dict["Z" + (i + 1).ToString().PadLeft(3, '0')]);
                    }
                    v1[31] = 1;
                    Thread.Sleep(200);
                    res += SiemensPLC.Write(ADD + ".0", v1).IsSuccess ? 0 : 1;
                }
                catch (Exception)
                {
                    res = 1000;
                }
            }
            else
            {
                res = 999;
            }
            SiemensPLC.ConnectClose();
            return (res == 0 ? true : false);
        }

        private bool Connect2PLC()
        {
            if (SiemensPLC == null) return false;
            try
            {
                OperateResult res = SiemensPLC.ConnectServer();
                isConnected = res.IsSuccess;
            }
            catch (Exception)
            {
                isConnected = false;
            }
            if (!isConnected)
                pubcls.WriteLog(IP + "的PLC连接失败！请检查网络或PLC！");
            return isConnected;
        }

    }
}
